package com.atguigu.spark.util.req

import com.atguigu.spark.util.util.PropUtil
import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord}
import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.InputDStream
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
import org.apache.spark.streaming.{Duration, Seconds, StreamingContext}

import java.io.{File, PrintWriter}
import java.text.SimpleDateFormat

object Spark_Click_Trend {
  def main(args: Array[String]): Unit = {
    val ssc: StreamingContext = new StreamingContext(new SparkConf().setMaster("local[*]")
      .setAppName("spark-streaming")
      .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .set("spark.testing.memory", "2147480000"), Duration.apply(5000))

    val kafkaPara: Map[String, Object] = Map[String, Object](
      ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG -> PropUtil("kafka.brokers"),
      ConsumerConfig.GROUP_ID_CONFIG -> PropUtil("kafka.group"),
      "key.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
      "value.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer"
    )
    val kafkaDStream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils
      .createDirectStream[String, String](ssc, LocationStrategies.PreferConsistent,
        ConsumerStrategies.Subscribe[String, String](Set(PropUtil("kafka.topic")), kafkaPara))
    kafkaDStream.map(x => {
      val str: String = x.value()
      val strs: Array[String] = str.split(" ")
      // timestamp area city userid adid
      val dayTs: Long = strs(0).toLong / 1000 / 10 * 10 * 1000
      (dayTs, 1)
    }).window(Seconds(60), Seconds(10)).reduceByKey(_ + _).foreachRDD(
      rdd => {
        val sdf = new SimpleDateFormat("mm:ss")
        val objArray: Array[String] = rdd.collect().sortBy(_._1).map(
          x => {
            //            { "xtime":"00:00", "yval":"156" }
            s"""
               |{ "xtime":"${sdf.format(x._1)}", "yval":${x._2}}
               |""".stripMargin
          }
        )
        val pw: PrintWriter = new PrintWriter(new File("D:\\WebSite\\bigData2\\adclick\\adclick.json"))
        pw.println("[")
        pw.println(objArray.mkString(" , "))
        pw.println("]")
        pw.flush()
      }
    )
    ssc.start()
    ssc.awaitTermination()
  }
}
